package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.entity.TbOrdersRefund;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.mapper.TbOrdersRefundMapper;
import com.robotserver.orders.param.TbOrderRefundSyncParam;
import com.robotserver.orders.service.*;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.request.TbkScOrderRefundGetRequest;
import com.taobao.api.request.TbkScRelationRefundRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import com.taobao.api.response.TbkScOrderRefundGetResponse;
import com.taobao.api.response.TbkScRelationRefundResponse;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Auther: liuqi
 * @Date: 2021/4/28 11:16
 * @Description:
 */
@Service
public class TbOrderRefundSyncServiceImpl implements TbOrderRefundSyncService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderRefundSyncServiceImpl.class);

    @Autowired
    private TbOrdersRefundMapper tbOrdersRefundMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private OrdersNotifyService ordersNotifyService;

    private static long pagesize = 100;
    private static long jumptype = 1;  // 向前翻页

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client) {
        syncAlimmUnitOrder(tbkOrderTimeVOList,alimmTokens,client);
    }

    @Override
    public void syncAlimmUnitOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client) {
        for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
            //syncTimeUnitOrder(tbkOrderTimeVO,alimmTokens,client,1l);
            //新版API全量下载维权订单
            syncTimeUnitOrder_new(tbkOrderTimeVO,alimmTokens,client,1l, null);
        }
    }

    /**
     * 旧版下载维权订单
     * @author jitwxs
     * @date 2023/2/6 18:17
     * @param tbkOrderTime
     * @param alimmTokens
     * @param client
     * @param pageNo
     */
    @Override
    public void syncTimeUnitOrder(TbkOrderTimeVO tbkOrderTime, AlimmTokens alimmTokens, TaobaoClient client, Long pageNo) {
        try {
            //淘宝联盟限流-单个联盟每1秒调用1次
            boolean inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_refund_token_ratelimit,1);
            //判断最多循环40次，每次睡眠50毫秒，总共1秒
            int flag = 0;
            while (!inRateLimit){
                flag ++;
                if(flag>40){
                    //对象转成JSON字符串，保存到redis队列中
                    AlimmTokens alimmTokens_new = new AlimmTokens();
                    BeanUtils.copyProperties(alimmTokens, alimmTokens_new);
                    alimmTokens_new.setBeginTime(Long.valueOf(DateUtil.getTime(DateFormatUtil.StringToDateFormat(tbkOrderTime.getBeginTime()))));
                    alimmTokens_new.setEndTime(Long.valueOf(DateUtil.getTime(DateFormatUtil.StringToDateFormat(tbkOrderTime.getEndTime()))));
                    String alimmTokensStr = JSONObject.toJSONString(alimmTokens_new);
                    //redisTemplate.opsForList().leftPush(alimmTokens_new.getRedisQueueKey(), alimmTokensStr);
                    return;
                }
                Thread.sleep(50);
                inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_refund_token_ratelimit, 1);
            }

            TbkScRelationRefundRequest req = new TbkScRelationRefundRequest();
            TbkScRelationRefundRequest.TopApiRefundRptOption obj = new TbkScRelationRefundRequest.TopApiRefundRptOption();
            obj.setPageSize(pagesize);
            obj.setSearchType(Long.valueOf(alimmTokens.getType()));
            obj.setRefundType(0L);  //1 表示2方，2表示3方，0表示不限
            obj.setStartTime(DateFormatUtil.StringToDateFormat(tbkOrderTime.getBeginTime()));
            obj.setPageNo(pageNo);
            obj.setBizType(alimmTokens.getOrderScene());
            req.setSearchOption(obj);
            TbkScRelationRefundResponse rsp = client.execute(req,alimmTokens.getAccessToken());

            SimpleDateFormat tbkFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
            //String downTime = tbkFormat.format(new Date());

            //logger.info("---orderScene="+alimmTokens.getOrderScene()+"::token=" + alimmTokens.getAccessToken() +"::" + tbkOrderTime.getBeginTime() +"::" + tbkOrderTime.getEndTime() );

            //系统繁忙，
            if("isp.call-limited".equals(rsp.getSubCode())){
                logger.error("--维权订单下载限流--重新将此token推入到redis当中-------orderScene="+alimmTokens.getOrderScene()+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
                //对象转成JSON字符串，保存到redis队列中
                //String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                //redisTemplate.opsForList().leftPush(alimmTokens.getRedisQueueKey(), alimmTokensStr);
                //发送报警消息
                //String content = "--error--维权订单-下载限流--下载时间="+ downTime +"::userName="+alimmTokens.getUserName() + "::bizType=" + alimmTokens.getOrderScene() +"::searchType="+ alimmTokens.getType() +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo+"::subMsg=" + rsp.getSubMsg();
                //ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
            }else{
//                //下载成功，监控 捕风客003 下载频率
//                if(alimmTokens.getUserName().equals("捕风客003")){
//                    String content = "--success--维权订单-下载成功--下载时间="+ downTime +"::userName="+alimmTokens.getUserName() + "::bizType=" + alimmTokens.getOrderScene() +"::searchType="+ alimmTokens.getType() +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo;
//                    ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
//                }
            }

            // 处理入库
            if (rsp.getResult() != null && rsp.getResult().getData() != null && rsp.getResult().getData().getResults() != null){
                //该页有订单数量
                if(rsp.getResult().getData().getResults().size() > 0){
                    for (TbkScRelationRefundResponse.Result result : rsp.getResult().getData().getResults()){
                        try {
                            orderAdd(result, alimmTokens);
                        } catch (Exception e) {
                            logger.error("淘宝维权订单入库失败-订单号:" +  result.getTbTradeParentId()+"::"+result.getTbTradeId()+ ",异常信息:", e);
                        }
                    }
                    pageNo = pageNo + 1;
                    syncTimeUnitOrder(tbkOrderTime,alimmTokens,client,pageNo);
                }
            }
        } catch (Exception e) {
            logger.error("sync tb settlement order err:",e);
        }
    }

    @Transactional
    @Override
    public void orderAdd(TbkScRelationRefundResponse.Result result, AlimmTokens alimmTokens) {
        int now = DateUtil.getNowTime();
        // 查询订单是否存在
        TbOrdersRefund tbOrdersRefund = tbOrdersRefundMapper.selectByTradeId(String.valueOf(result.getTbTradeParentId()), String.valueOf(result.getTbTradeId()));
        if (tbOrdersRefund != null){
            //查看时间是否一样，如果不一样，则修改
            if(tbOrdersRefund.getModifiedTime().intValue() != DateUtil.getTime(result.getModifiedTime())){
                //修改
                logger.info("---TBOrdersRefund update: parentId: {}, childId: {},tkstatus:{},modifytime:{}",new Object[]{result.getTbTradeParentId(),result.getTbTradeId(),result.getRefundStatus().intValue(),DateUtil.getTime(result.getModifiedTime())});
                tbOrdersRefund.setTbTradeParentId(String.valueOf(result.getTbTradeParentId()));
                tbOrdersRefund.setSpecialId(result.getSpecialId());
                tbOrdersRefund.setRelationId(result.getRelationId());
                tbOrdersRefund.setTk3rdPubId(result.getTk3rdPubId());
                tbOrdersRefund.setTkPubId(result.getTkPubId());
                tbOrdersRefund.setTkSubsidyFeeRefund3rdPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund3rdPub()));
                tbOrdersRefund.setTkCommissionFeeRefund3rdPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund3rdPub()));
                tbOrdersRefund.setTkSubsidyFeeRefundPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefundPub()));
                tbOrdersRefund.setTkCommissionFeeRefundPub(Math.currencyFormatToF(result.getTkCommissionFeeRefundPub()));
                tbOrdersRefund.setTkRefundSuitTime(DateUtil.getTime(result.getTkRefundSuitTime()));
                tbOrdersRefund.setTkRefundTime(DateUtil.getTime(result.getTkRefundTime()));
                tbOrdersRefund.setEarningTime(DateUtil.getTime(result.getEarningTime()));
                tbOrdersRefund.setTbTradeCreateTime(DateUtil.getTime(result.getTbTradeCreateTime()));
                tbOrdersRefund.setRefundStatus(result.getRefundStatus().intValue());
                tbOrdersRefund.setTbAuctionTitle(result.getTbAuctionTitle());
                tbOrdersRefund.setTbTradeId(String.valueOf(result.getTbTradeId()));
                tbOrdersRefund.setRefundFee(Math.currencyFormatToF(result.getRefundFee()));
                tbOrdersRefund.setTbTradeFinishPrice(Math.currencyFormatToF(result.getTbTradeFinishPrice()));
                tbOrdersRefund.setTkPubShowReturnFee(Math.currencyFormatToF(result.getTkPubShowReturnFee()));
                tbOrdersRefund.setTk3rdPubShowReturnFee(Math.currencyFormatToF(result.getTk3rdPubShowReturnFee()));
                tbOrdersRefund.setRefundType(result.getRefundType().intValue());
                tbOrdersRefund.setAlscPid(result.getAlscPid());
                tbOrdersRefund.setAlscId(result.getAlscId());
                tbOrdersRefund.setModifiedTime(DateUtil.getTime(result.getModifiedTime()));
                tbOrdersRefund.setUpdateTime(now);
                tbOrdersRefund.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                tbOrdersRefund.setAlimmUserName(alimmTokens.getUserName());

                //修改维权订单
                tbOrdersRefundMapper.update(tbOrdersRefund);
            }
        }else{
            //只添加状态为：'4-维权创建(淘客结算回执);2-维权成功(淘客结算回执);3-维权失败(淘客结算回执)
            //if (result.getRefundStatus().longValue() == 4 || result.getRefundStatus().longValue() == 2 || result.getRefundStatus().longValue() == 3){
            logger.info("---TBOrderRefund add:parentId: {},childId: {},tkstatus:{}",new Object[]{result.getTbTradeParentId(),result.getTbTradeId(),result.getRefundStatus().intValue()});
            TbOrdersRefund tbOrdersRefund_new = new TbOrdersRefund();
            tbOrdersRefund_new.setId(IdWorker.getId());
            tbOrdersRefund_new.setTbTradeParentId(String.valueOf(result.getTbTradeParentId()));
            tbOrdersRefund_new.setSpecialId(result.getSpecialId());
            tbOrdersRefund_new.setRelationId(result.getRelationId());
            tbOrdersRefund_new.setTk3rdPubId(result.getTk3rdPubId());
            tbOrdersRefund_new.setTkPubId(result.getTkPubId());
            tbOrdersRefund_new.setTkSubsidyFeeRefund3rdPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund3rdPub()));
            tbOrdersRefund_new.setTkCommissionFeeRefund3rdPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund3rdPub()));
            tbOrdersRefund_new.setTkSubsidyFeeRefundPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefundPub()));
            tbOrdersRefund_new.setTkCommissionFeeRefundPub(Math.currencyFormatToF(result.getTkCommissionFeeRefundPub()));
            tbOrdersRefund_new.setTkRefundSuitTime(DateUtil.getTime(result.getTkRefundSuitTime()));
            tbOrdersRefund_new.setTkRefundTime(DateUtil.getTime(result.getTkRefundTime()));
            tbOrdersRefund_new.setEarningTime(DateUtil.getTime(result.getEarningTime()));
            tbOrdersRefund_new.setTbTradeCreateTime(DateUtil.getTime(result.getTbTradeCreateTime()));
            tbOrdersRefund_new.setRefundStatus(result.getRefundStatus().intValue());
            tbOrdersRefund_new.setTbAuctionTitle(result.getTbAuctionTitle());
            tbOrdersRefund_new.setTbTradeId(String.valueOf(result.getTbTradeId()));
            tbOrdersRefund_new.setRefundFee(Math.currencyFormatToF(result.getRefundFee()));
            tbOrdersRefund_new.setTbTradeFinishPrice(Math.currencyFormatToF(result.getTbTradeFinishPrice()));
            tbOrdersRefund_new.setTkPubShowReturnFee(Math.currencyFormatToF(result.getTkPubShowReturnFee()));
            tbOrdersRefund_new.setTk3rdPubShowReturnFee(Math.currencyFormatToF(result.getTk3rdPubShowReturnFee()));
            tbOrdersRefund_new.setRefundType(result.getRefundType().intValue());
            tbOrdersRefund_new.setAlscPid(result.getAlscPid());
            tbOrdersRefund_new.setAlscId(result.getAlscId());
            tbOrdersRefund_new.setModifiedTime(DateUtil.getTime(result.getModifiedTime()));
            tbOrdersRefund_new.setCreateTime(now);
            tbOrdersRefund_new.setUpdateTime(now);
            tbOrdersRefund_new.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
            tbOrdersRefund_new.setAlimmUserName(alimmTokens.getUserName());
            tbOrdersRefundMapper.insert(tbOrdersRefund_new);
            //}
        }
    }

    /**
     * 新版下载维权订单-全量下载
     * @author jitwxs
     * @date 2023/2/6 18:17
     * @param tbkOrderTime
     * @param alimmTokens
     * @param client
     * @param pageNo
     */
    @Override
    public void syncTimeUnitOrder_new(TbkOrderTimeVO tbkOrderTime, AlimmTokens alimmTokens, TaobaoClient client, Long pageNo, String positionIndex) {
        try {
            //淘宝联盟限流-单个联盟每2秒调用1次
            boolean inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_refund_token_ratelimit, 1);
            //判断最多循环40次，每次睡眠50毫秒，总共1秒
            int flag = 0;
            while (!inRateLimit){
                flag ++;
                if(flag>40){
                    //对象转成JSON字符串，保存到redis队列中
                    //String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                    //redisTemplate.opsForList().leftPush(alimmTokens.getRedisQueueKey(), alimmTokensStr);
                    return;
                }
                Thread.sleep(50);
                inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_refund_token_ratelimit ,1);
            }

            //新版全量下载维权订单
            TbkScOrderRefundGetRequest req = new TbkScOrderRefundGetRequest();
            TbkScOrderRefundGetRequest.PublisherRefundOrderQueryOption obj1 = new TbkScOrderRefundGetRequest.PublisherRefundOrderQueryOption();
            obj1.setJumpType(1L);         //跳转类型，当向前或者向后翻页必须提供,-1: 向前翻页,1：向后翻页
            obj1.setOrderScene(1L);       //1全部订单
            obj1.setPageSize(pagesize);   //单页订单量，1-100，上限100条
            obj1.setQueryType(Long.valueOf(alimmTokens.getType()));  //1-维权发起时间，2-订单结算时间（正向订单），3-维权完成时间，4-订单创建时间，5-订单更新时间 （注意：入参startTime小于2022年12月20日0点时，query_type只能为1、2、3；入参startTime大于等于2022年12月20日0点时，query_type可以为1、2、3、4、5)
            obj1.setPageNo(pageNo);       //查询页数
            obj1.setPositionIndex(positionIndex);   //位点，除第一页之外，都需要传递；前端原样返回。
            obj1.setStartTime(tbkOrderTime.getBeginTime());    //开始时间
            obj1.setMemberType(4L);                       //1 表示2方，2表示3方，4表示不限
            obj1.setEndTime(tbkOrderTime.getEndTime());     //结束时间
            req.setPublisherRefundOrderQueryOption(obj1);
            TbkScOrderRefundGetResponse rsp = client.execute(req, alimmTokens.getAccessToken());

            //系统繁忙，
            if("isp.call-limited".equals(rsp.getSubCode())){
                logger.error("--维权订单下载限流--重新将此token推入到redis当中-------orderScene="+alimmTokens.getOrderScene()+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
                //对象转成JSON字符串，保存到redis队列中
                //String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                //redisTemplate.opsForList().leftPush(alimmTokens.getRedisQueueKey(), alimmTokensStr);
                //发送报警消息
                //String content = "--error--维权订单-下载限流--下载时间="+ downTime +"::userName="+alimmTokens.getUserName() + "::bizType=" + alimmTokens.getOrderScene() +"::searchType="+ alimmTokens.getType() +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo+"::subMsg=" + rsp.getSubMsg();
                //ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
            }else{
//                //下载成功，监控 捕风客003 下载频率
//                if(alimmTokens.getUserName().equals("捕风客003")){
//                    String content = "--success--维权订单-下载成功--下载时间="+ downTime +"::userName="+alimmTokens.getUserName() + "::bizType=" + alimmTokens.getOrderScene() +"::searchType="+ alimmTokens.getType() +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo;
//                    ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
//                }
            }

            // 处理入库
            if (rsp.getData() != null && rsp.getData().getResult() != null){
                //该页有订单数量
                if(rsp.getData().getResult().size() > 0){
                    for (TbkScOrderRefundGetResponse.PublisherRefundOrderDTO result: rsp.getData().getResult()){
                        try {
                            orderAdd_new(result, alimmTokens);
                        } catch (Exception e) {
                            logger.error("淘宝维权订单入库失败-订单号:" +  result.getTbTradeParentId()+"::"+result.getTbTradeId()+ ",异常信息:", e.getMessage());
                        }
                    }
                    pageNo = pageNo + 1;
                    syncTimeUnitOrder_new(tbkOrderTime,alimmTokens,client,pageNo, rsp.getData().getPositionIndex());
                }
            }
        } catch (Exception e) {
            logger.error("sync tb settlement order err:",e);
        }
    }

    @Transactional
    @Override
    public void orderAdd_new(TbkScOrderRefundGetResponse.PublisherRefundOrderDTO result, AlimmTokens alimmTokens) {
        int now = DateUtil.getNowTime();
        // 查询订单是否存在
        TbOrdersRefund tbOrdersRefund = tbOrdersRefundMapper.selectByTradeId(String.valueOf(result.getTbTradeParentId()), String.valueOf(result.getTbTradeId()));
        if (tbOrdersRefund != null){
            //查看时间是否一样，如果不一样，则修改
            int modifiedTime = DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getModifiedTime()));

            if(tbOrdersRefund.getModifiedTime().intValue() != modifiedTime){
                //修改
                logger.info("---TBOrdersRefund update: parentId: {}, childId: {},tkstatus:{},modifytime:{}",new Object[]{result.getTbTradeParentId(),result.getTbTradeId(),result.getRefundStatus().intValue(), modifiedTime});
                tbOrdersRefund.setTbTradeParentId(String.valueOf(result.getTbTradeParentId()));
                tbOrdersRefund.setSpecialId(result.getSpecialId());
                tbOrdersRefund.setRelationId(result.getRelationId());
                //tbOrdersRefund.setTk3rdPubId(result.getTk3rdPubId());
                //tbOrdersRefund.setTkPubId(result.getTkPubId());
                tbOrdersRefund.setTkSubsidyFeeRefund3rdPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund()));
                tbOrdersRefund.setTkCommissionFeeRefund3rdPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund()));
                tbOrdersRefund.setTkSubsidyFeeRefundPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund()));
                tbOrdersRefund.setTkCommissionFeeRefundPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund()));
                tbOrdersRefund.setTkRefundSuitTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTkRefundSuitTime())));
                tbOrdersRefund.setTkRefundTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTkRefundTime())));
                tbOrdersRefund.setEarningTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getEarningTime())));
                tbOrdersRefund.setTbTradeCreateTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTbTradeCreateTime())));
                tbOrdersRefund.setRefundStatus(result.getRefundStatus().intValue());
                tbOrdersRefund.setTbAuctionTitle(result.getItemTitle());
                tbOrdersRefund.setTbTradeId(result.getTbTradeId());
                tbOrdersRefund.setRefundFee(Math.currencyFormatToF(result.getRefundFee()));
                tbOrdersRefund.setTbTradeFinishPrice(Math.currencyFormatToF(result.getTbTradeFinishPrice()));
                tbOrdersRefund.setTkPubShowReturnFee(Math.currencyFormatToF(result.getShowReturnFee()));
                tbOrdersRefund.setTk3rdPubShowReturnFee(Math.currencyFormatToF(result.getShowReturnFee()));
                if("二方".equals(result.getTkOrderRole())){
                    tbOrdersRefund.setRefundType(1); //1 表示2方，2表示3方
                }else{
                    tbOrdersRefund.setRefundType(2); //1 表示2方，2表示3方
                }
                //tbOrdersRefund.setAlscPid(result.getAlscPid());
                //tbOrdersRefund.setAlscId(result.getAlscId());
                tbOrdersRefund.setModifiedTime(modifiedTime);
                tbOrdersRefund.setUpdateTime(now);
                tbOrdersRefund.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                tbOrdersRefund.setAlimmUserName(alimmTokens.getUserName());

                //修改维权订单
                tbOrdersRefundMapper.update(tbOrdersRefund);
            }
        }else{
            //只添加状态为：'4-维权创建(淘客结算回执);2-维权成功(淘客结算回执);3-维权失败(淘客结算回执)
            //if (result.getRefundStatus().longValue() == 4 || result.getRefundStatus().longValue() == 2 || result.getRefundStatus().longValue() == 3){
            logger.info("---TBOrderRefund add:parentId: {},childId: {},tkstatus:{}",new Object[]{result.getTbTradeParentId(),result.getTbTradeId(),result.getRefundStatus().intValue()});
            TbOrdersRefund tbOrdersRefund_new = new TbOrdersRefund();
            tbOrdersRefund_new.setId(IdWorker.getId());
            tbOrdersRefund_new.setTbTradeParentId(String.valueOf(result.getTbTradeParentId()));
            tbOrdersRefund_new.setSpecialId(result.getSpecialId());
            tbOrdersRefund_new.setRelationId(result.getRelationId());
            //tbOrdersRefund_new.setTk3rdPubId(result.getTk3rdPubId());
            //tbOrdersRefund_new.setTkPubId(result.getTkPubId());
            tbOrdersRefund_new.setTkSubsidyFeeRefund3rdPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund()));
            tbOrdersRefund_new.setTkCommissionFeeRefund3rdPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund()));
            tbOrdersRefund_new.setTkSubsidyFeeRefundPub(Math.currencyFormatToF(result.getTkSubsidyFeeRefund()));
            tbOrdersRefund_new.setTkCommissionFeeRefundPub(Math.currencyFormatToF(result.getTkCommissionFeeRefund()));
            tbOrdersRefund_new.setTkRefundSuitTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTkRefundSuitTime())));
            tbOrdersRefund_new.setTkRefundTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTkRefundTime())));
            tbOrdersRefund_new.setEarningTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getEarningTime())));
            tbOrdersRefund_new.setTbTradeCreateTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getTbTradeCreateTime())));
            tbOrdersRefund_new.setRefundStatus(result.getRefundStatus().intValue());
            tbOrdersRefund_new.setTbAuctionTitle(result.getItemTitle());
            tbOrdersRefund_new.setTbTradeId(String.valueOf(result.getTbTradeId()));
            tbOrdersRefund_new.setRefundFee(Math.currencyFormatToF(result.getRefundFee()));
            tbOrdersRefund_new.setTbTradeFinishPrice(Math.currencyFormatToF(result.getTbTradeFinishPrice()));
            tbOrdersRefund_new.setTkPubShowReturnFee(Math.currencyFormatToF(result.getShowReturnFee()));
            tbOrdersRefund_new.setTk3rdPubShowReturnFee(Math.currencyFormatToF(result.getShowReturnFee()));
            if("二方".equals(result.getTkOrderRole())){
                tbOrdersRefund_new.setRefundType(1); //1 表示2方，2表示3方
            }else{
                tbOrdersRefund_new.setRefundType(2); //1 表示2方，2表示3方
            }
            //tbOrdersRefund_new.setAlscPid(result.getAlscPid());
            //tbOrdersRefund_new.setAlscId(result.getAlscId());
            tbOrdersRefund_new.setModifiedTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(result.getModifiedTime())));
            tbOrdersRefund_new.setCreateTime(now);
            tbOrdersRefund_new.setUpdateTime(now);
            tbOrdersRefund_new.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
            tbOrdersRefund_new.setAlimmUserName(alimmTokens.getUserName());
            tbOrdersRefundMapper.insert(tbOrdersRefund_new);
        }
    }

}
